<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
<!--        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>-->
      </template>
      <template  #menu="{row,index}">
        <el-button type="primary"
                   icon="el-icon-edit"
                   text
                   v-if='row.adminUserId==userId'
                   @click="$refs.crud.rowEdit(row,index)">编 辑
        </el-button>
        <el-button type="danger"
                   icon="el-icon-delete"
                   text
                   v-if='row.adminUserId==userId'
                   @click="$refs.crud.rowDel(row,index)">删 除
        </el-button>
        <el-button
          type="primary"
          text
          icon="el-icon-plus"
          v-if='row.adminUserId==userId'
          @click.stop="handleUser(row,index)"
        >成员管理
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="成员管理" append-to-body v-model="workuserBox">
      <avue-crud
        :option="useroption"
        :table-loading="workuserLoading"
        :data="workuserData"
        ref="workuserCrud"
        v-model="workuserForm"
        :before-open="workuserBeforeOpen"
        v-model:page="workuserPage"
        @search-change="workuserSearchChange"
        @search-reset="workuserSearchReset"
        @selection-change="workuserSelectionChange"
        @current-change="workuserCurrentChange"
        @size-change="workuserSizeChange"
        @refresh-change="workuserRefreshChange"
        @on-load="workuserOnLoad"
      >
        <template #menu-left>
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="handleUserAdd">新 增
          </el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     plain
                     @click="handleUserDelete">删 除
          </el-button>
        </template>
        <template  #menu="scope">
          <el-button
            type="primary"
            text
            icon="el-icon-delete"
            @click.stop="handleUserRemove(scope.row,scope.index)"
          >删除
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>

    <el-dialog title="成员新增" append-to-body v-model="workuserInsert">
      <avue-form
        ref="workuserInsertForm"
        :option="insertoption"
        v-model="workuserInsertForm"
        @submit='handleUserSubmit'
      >
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getWorkUserList,
  addWorkUser,
  removeWorkUser
} from '@/api/system/workspace';
import { getDeptTree } from '@/api/system/dept';
  import {mapGetters} from "vuex";
import website from '@/config/website';
  export default {
    data() {
      return {
        userId:'',
        workuserBox:false,
        workuserInsert:false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        workuserSelectionList: [],
        workuserLoading: false,
        workuserData: [],
        workuserForm: {},
        workuserInsertForm: {},
        workuserPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0,
        },
        workuserQuery : {},
        insertoption:{
          column: [

            {
              label: "所属部门",
              prop: "deptId",
              type: "tree",
              span:24,
              multiple: false,
              cell: true,
              cascader: ['userName'],
              dicData: [],
              props: {
                label: "title",
                value:"id"
              },
              checkStrictly: true,
              slot: true,
              rules: [{
                required: true,
                message: "请选择所属部门",
                trigger: "click"
              }],
              nodeClick: (node) => {
                this.workuserInsertForm.deptName = node.title;
              }
            },

            {
              label: "人员姓名",
              prop: "userName",
              type: "tree",
              span:24,
              multiple: false,
              cell: true,
              dicUrl: `/blade-user/search/deptid?deptId={{key}}`,
              props: {
                label: "title",
                value:"title",
              },
              checkStrictly: true,
              slot: true,
              rules: [{
                required: true,
                message: "请选择所属部门",
                trigger: "click"
              }],
              nodeClick: (node) => {
                this.workuserInsertForm.userId = node.id;
              }
            },

          ]
        },
        useroption: {
          height: 'auto',
          calcHeight: 140,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          viewBtn: false,
          editBtn:false,
          delBtn:false,
          addBtn:false,
          dialogType: 'drawer',
          menuWidth: '100px',
          dialogClickModal: false,
          column: [
            {
              label: '登录账号',
              prop: 'account',
              search: true,
              display: false,
            },
            {
              label: '用户姓名',
              prop: 'realName',
              search: true,
              display: false,
            },
            {
              label: '所属角色',
              prop: 'roleName',
              slot: true,
              display: false,
            },
            {
              label: '所属部门',
              prop: 'deptName',
              slot: true,
              display: false,
            },

          ]
        },
        option: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          delBtn: false,
          editBtn: false,
          selection: true,
          menuWidth:'350px',
          dialogClickModal: false,
          column: [

            {
              label: "名称",
              prop: "name",
              span: 24,
              search: true,
              rules: [{
                required: true,
                message: "请输入岗位名称",
                trigger: "blur"
              }]
            },
            {
              label: '管理员',
              type: 'tree',
              prop: "adminUserId",
              dicUrl: `/blade-user/user-list`,
              props: {
                label: "name",
                value: "id"
              },
              span: 24,
              nodeClick:(data)=>{
                this.form.adminUser = data.name
              },
              rules: [
                {
                  required: true,
                  message: '请选择管理员',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: "描述",
              prop: "remark",
              type: "textarea",
              span: 24,
              minRows: 6,
            },

            {
              label: "创建时间",
              prop: "createTime",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入创建时间",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission","userInfo"]),

      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      idss() {
        let idss = [];
        this.workuserSelectionList.forEach(ele => {
          idss.push(ele.id);
        });
        return idss.join(",");
      }
    },
    mounted() {
      getDeptTree(website.tenantId).then(res => {
        const column = this.findObject(this.insertoption.column, "deptId");
        column.dicData = res.data.data;
      });

      this.userId = this.$store.getters.userInfo.user_id;
    },
    methods: {
      handleUser(row, index){
        this.workspaceId = row.id;
        this.workuserBox = true;
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleUserRemove(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeWorkUser(row.id,this.workspaceId);
          })
          .then(() => {
            this.workuserRefreshChange();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleUserAdd(){
        this.workuserInsertForm= { };
        this.workuserInsert = true;
        this.$nextTick(()=>{this.$refs.workuserInsertForm.resetForm();})

      },
      handleUserSubmit(row, done){
        addWorkUser(this.workuserInsertForm.userId,this.workspaceId).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });

          this.workuserRefreshChange();
          this.workuserInsert = false;
        }, error => {
          window.console.log(error);
          loading();
        });
        done();
      },
      handleUserDelete() {
        if (this.workuserSelectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeWorkUser(this.idss,this.workspaceId);
          })
          .then(() => {
            this.workuserRefreshChange();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.workuserCrud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      workuserRowUpdate(row, index, done, loading) {
        updateworkuser(row.id, row.userType, row.userExt).then(
          () => {
            this.workuserOnLoad(this.workuserPage);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            done();
          },
          error => {
            window.console.log(error);
            loading();
          }
        );
      },
      workuserBeforeOpen(done, type) {

      },
      workuserSearchReset() {
        this.workuserQuery = {};
        this.workuserOnLoad(this.workuserPage);
      },
      workuserSearchChange(params, done) {
        this.workuserQuery = params;
        this.workuserPage.currentPage = 1;
        this.workuserOnLoad(this.workuserPage, params);
        done();
      },
      workuserSelectionChange(list) {
        this.workuserSelectionList = list;
      },
      workuserSelectionClear() {
        this.workuserSelectionList = [];
        this.$refs.workuserCrud.toggleSelection();
      },
      workuserCurrentChange(currentPage) {
        this.workuserPage.currentPage = currentPage;
      },
      workuserSizeChange(pageSize) {
        this.workuserPage.pageSize = pageSize;
      },
      workuserRefreshChange() {
        this.workuserOnLoad(this.workuserPage, this.workuserQuery);
      },
      workuserOnLoad(page, params = {}) {
        this.workuserLoading = true;
        getWorkUserList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.workuserQuery),
          this.workspaceId
        ).then(res => {
          const data = res.data.data;
          this.workuserPage.total = data.total;
          this.workuserData = data.records;
          this.workuserLoading = false;
          this.selectionClear();
        });
      },
    }
  };
</script>

<style>
</style>
